package com.xiaoming.mojbackenserviceclient.client;


import com.xiaoming.mojbackendcommon.common.ErrorCode;
import com.xiaoming.mojbackendcommon.constant.UserConstant;
import com.xiaoming.mojbackendcommon.exception.BusinessException;
import com.xiaoming.mojbackendmodel.model.entity.User;
import com.xiaoming.mojbackendmodel.model.enums.UserRoleEnum;
import com.xiaoming.mojbackendmodel.model.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

import static com.xiaoming.mojbackendcommon.constant.UserConstant.USER_LOGIN_STATE;

@FeignClient(value = "user-service",path = "/api/user/inner")
public interface UserClient {
    @GetMapping("/get/id")
    public User getById(@RequestParam("userId") Long userId);

    @GetMapping("/get/ids")
    public List<User> listByIds(@RequestParam("idList") Collection<Long> idList);

    default UserVO getUserVO(User user)
    {
        if (user==null)
        {
            return null;
        }
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return userVO;
    }

    default  boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }
    default User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 在这里做全局权限校验
        return currentUser;
    }





}

